<?php 
if (!isset($_SESSION)) {
  session_start();
}
define("CCTRL", "gallery");
define("CCTRLNAME", "gallery");
define("TOKEN", "4ab837664a8e17b1bec62a758a68b7ac");
include APPPATH . 'libraries/defu.php';
class gallery extends CI_Controller  {

        /**
        * Index Page for this controller.
        *
        * Maps to the following URL
        * 		http://example.com/index.php/welcome
        *	- or -  
        * 		http://example.com/index.php/welcome/index
        *	- or -
        * Since this controller is set as the default controller in 
        * config/routes.php, it's displayed at http://example.com/
        *
        * So any other public methods not prefixed with an underscore will
        * map to /index.php/welcome/<method_name>
        * @see http://codeigniter.com/user_guide/general/urls.html
        */
        function __construct()
        {
            parent::__construct();
            $this->load->helper('url');
            $this->load->model('backend/gallery_model');
            $this->gallery_model=new gallery_model();
            $this->load->model('backend/backend_model');
            $this->backend_model=new backend_model("_gallery");
            $this->load->model('colmod/gallery_colmod');
            $this->colModel=new gallery_colmod();
            $this->load->library('smarty3');
            $this->smarty=new CI_Smarty3();
            $this->smarty->error_reporting = E_ALL & ~E_NOTICE;
            if(!isset($_SESSION["ADP"][CCTRL]["display"]))$_SESSION["ADP"][CCTRL]["display"]=0;
        }
        function captcha(){
            
            $this->load->helper('captcha');
            $vals = array(
                //'word'          => rand(),
                'img_path'	=> './captcha/',
                'img_url'	=> base_url()."captcha/",
                //'font_path'	=> base_url().'f/elephant.ttf',
                'img_width'	=> '100',
                'img_height'    => 32,
                'border'        => 0,
                'expiration'    => 3600,
                'time'          =>time(),
                "randomcolor"   =>false,
                "legnth"        =>4
                );

            $cap = create_captcha($vals);
            echo $cap['image'];
            //echo $cap['word'];['src']
        }
        function index(){
            
            if(!isset($_SESSION["ADP"]["USER"])){
                $this->smarty->display("backend/00_login"); 
                return;
            }
            if(!checkAuthority(CCTRLNAME)){
                $this->smarty
                        ->assign('_SESSION', $_SESSION)
                        ->display("backend/00_accessdenied");
                return;
            }
            $this->smarty
                    ->assign('_SESSION', $_SESSION)
                    ->display("backend/".CCTRL."/".CCTRL);
        }
        function gridscript(){
            //unset($_SESSION["ADP"][CCTRL."-JQX"]);
            if(isset($_SESSION["ADP"][CCTRL."-JQX"]["colModel"]))
                $colModel=$_SESSION["ADP"][CCTRL."-JQX"]["colModel"];
            else{
                $colModel=$this->colModel->get();
                $_SESSION["ADP"][CCTRL."-JQX"]["colModel"]=$colModel;
            }
            header("Content-type:text/javascript");
            $this->smarty
                    ->assign("colModel", $colModel)
                    ->assign("display",$_SESSION["ADP"][CCTRL]["display"])
                    ->display("backend/00_base/grid_advanced");
        }
        function handleEvent(){
            header("Content-type:text/javascript");
            $this->smarty
                    ->display("backend/".CCTRL."/handleEvent");
        }
        function edit($_id=""){
            $Data=null;
            if($_id!=""){
                $tmp=$this->backend_model->get($_id);
                if(count($tmp)>0){
                    $Data["OBJ"]=$tmp[0];
                    $Data["oGalleryDetail"]=$this->gallery_model->getDetails($Data["OBJ"]->_id,$Data["OBJ"]->_amount);
                }
            }
            $this->smarty
                    ->assign('_SESSION', $_SESSION)
                    ->assign("Data", $Data)
                    ->display("backend/".CCTRL."/02_edit");
        }
        function save(){
            $_id    =$this->input->post("_id");
            $_alias =$this->input->post("_alias");
            $_name  =$this->input->post("_name");
            $_thumb =$this->input->post("_thumb");
            $_des   =$this->input->post("_des");
            $_imgs  =$this->input->post("_imgs");
            $messages=array();
            if($_name===false || $_name == ""){
                $messages[]    =   "[Shound be non-empty] Title không được để trống.";
            }
            if($_alias===false || convertUrl($_alias) == ""){
                $messages[]    =   "[Shound be non-empty] Alias không được để trống.";
            }
            if($_imgs===false || $_imgs == ""){
                $messages[]    =   "[Shound be non-empty] Images không được để trống.";
            }elseif(!is_array($_imgs) || count($_imgs)==0){
                $messages[]    =   "[Shound be non-empty] Images không được để trống.";
            }
            if(count($messages)>0){
                $result   =   -1;
                $message    =   implode("<br/>", $messages);
                goto result;
            }
            $params=array(
                "_name"         =>  $_name,
                "_thumb"        =>  $_thumb,
                "_amount"       =>  count($_imgs),
                "_alias"        =>  convertUrl($_alias)
            );
            $rsf=false;
            if(!@checkAuthority(CCTRL,false)){
                    $result=-1;
                    $message="[Access Denied] Bạn không có quyền thực hiện thao tác này.<br/> Mọi thay đổi dữ liệu đều không được công nhận.";
                    goto result;
            }elseif($_id==false){
                $_galleryid=strtoupper(md5(time().microtime ()));
                $params["_id"]  = $_galleryid;
                $params["_insert"]  = date("Y-m-d H:i:s");
                $this->db->trans_begin();
                $rsf=$this->backend_model->insert($params);
            }else{
                $_galleryid=$_id;
                $params["_update"]  = date("Y-m-d H:i:s");
                $this->db->trans_begin();
                $rsf=$this->backend_model->update($_id,$params);
            }
            $rss=true;
            $oGallerydetail=new backend_model("_gallery_detail");
            foreach($_imgs as $_i){
                $aParams=array(
                    "_galleryid"=>$_galleryid,
                    "_image"=>$_i[0],
                    "_title"=>$_i[1],
                    "_insert"=>date("Y-m-d H:i:s")
                );
                $aUpdates=array("_title","_insert");
                if(!$oGallerydetail->insert_onduplicate_update($aParams, $aUpdates)){
                    $rss=false;
                    break;
                }
            }
            
            if ($rsf===false || $rss===false || @$this->db->trans_status() === FALSE){
                @$this->db->trans_rollback();
                $result     =   -888;
                $message    =   "[Fail] Please check your data input and try again.<br/><br/>
                    Find out more about an <span class='csp'><tt onclick='_whyerror()'>Error Message</tt></span>
                    ";
            }else{
                @$this->db->trans_commit();
                $alog=array(
                    "_table"=>"Product",
                    "_row"=>null,
                    "_commandtype"=>$_id==false?"insert":"update",
                    "_log"=>print_r(array(
                        "user" =>$_SESSION["ADP"]["USER"]["Name"],
                        "ip"=>  getIP(),
                        "command"=>$_id==false?"insert":"update",
                        "id"    =>$_id
                    ),true)
                );
                @$this->backend_model->tolog($alog);
                $result     =   1;
                $message    =   "[Success] Thành công.";
            }
            result:
            echo json_encode(array("result"=>$result,"message"=>$message));
        }
        function binding(){
            $data_rows=array();
            $result=$this->gallery_model->binding();
//            for ($i=0;$i<count($result['rows']);$i++) {
//                $result['rows'][$i]->Status = ($result['rows'][$i]->Status=="true" || $result['rows'][$i]->Status=="Public")?true:false;
//            }
            $data[] = array(
                'TotalRows' => $result['total_rows'],
                'Rows' => $result['rows']
            );
            echo json_encode($data);
        }
        
}
?>
